//
//  UITextView+Emoticon.swift
//  KeyboardDemo
//
//  Created by Lucky on 16/5/15.
//  Copyright © 2016年 Lucky. All rights reserved.
//

import UIKit

extension UITextView {
    func insertEmoticon(emoticon: Emoticon) {
        
        //删除按钮处理
        if emoticon.isRemoveButton {
            deleteBackward()
        }
        
        //判断是否是emoji
        if emoticon.emojiStr != nil {
            self.replaceRange(self.selectedTextRange!, withText: emoticon.emojiStr!)
        }
        
        if emoticon.png != nil {
            //创建属性字符串
            let imageText = EmoticonAttachment.imageText(emoticon, font: font!)
            //拿到当前所有内容
            let strM = NSMutableAttributedString(attributedString: self.attributedText)
            //插入表情到当前光标所在的位置
            let range = self.selectedRange
            strM.replaceCharactersInRange(range, withAttributedString: imageText)
            //设置属性字符串的尺寸
            strM.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(range.location, 1))
            //替换文字
            self.attributedText = strM
            //恢复光标所在的位置
            self.selectedRange = NSMakeRange(range.location + 1, 0)
            //触发textView的文字改变代理方法
            delegate?.textViewDidChange!(self)
        }
    }
    
    func emoticonAttributedText() -> String {
        
        var strM = String()
        
        attributedText.enumerateAttributesInRange(NSMakeRange(0, attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (objc, range, _) in
            
            if objc["NSAttachment"] != nil {
                let attachment = objc["NSAttachment"] as! EmoticonAttachment
                strM += attachment.chs!
            } else {
                strM += (self.text as NSString).substringWithRange(range)
            }
            
        }
        
        return strM
    }
}

